# -*- coding: utf-8 -*-

import os
import cgi
import urllib
import sys
import md5
import time
import Cookie

from django.utils import simplejson
from xml.dom import minidom

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch_errors import *
from google.appengine.api import users
from google.appengine.ext.db import Key
from google.appengine.ext.db import BadKeyError
from google.appengine.ext.webapp import template
from time import strftime

from alisoft import AliSoftAPI

from baseclass import BaseHandler
from model import Customer
from model import WishList

class CustomerCreate(BaseHandler):    
    def get(self):  
        template_values = {}      
        template_values["isp"] = self.getCookie('isp')
        template_values["ispuser"] = self.getCookie('ispuser')
        template_values["ispid"] = self.getCookie('ispid')
        info = str(self.response.headers.items())+"<hr>"
        template_values["info"] = info
        self.outputTemplate(template_values, "customer_create_view")
        
    def post(self):
        try:
            customer = Customer.queryByEmail(self.request.get("email"))
            if customer == None:
                customer = Customer()
                customer.name = self.request.get("name")
                customer.email = self.request.get("email")
                customer.secret = self.request.get("password")
                customer.isp = self.request.get("isp")
                customer.ispid = self.request.get("ispid")
                customer.status = Customer.ISPOK            
                customer.put()
                template_values = {'msg': 'OK '}
            else:
                template_values = {'msg': 'Error: This customer exists.'}
        except:
            template_values = {'msg': 'Error: '+str(sys.exc_info())}
        finally:
            self.outputTemplate(template_values, "customer_create_view")
            
class CustomerList(BaseHandler):
    def get(self):
        try:
            query = db.Query(Customer)
            query.order('name')
            items = query.fetch(999)
            if items:
                template_values = {"items": items}
            else:
                template_values = {"msg": "Not found."}
        except:
            template_values = {'msg': 'Error: '+str(sys.exc_info())}
        finally:
            self.outputTemplate(template_values, "customer_list_view")
            

application = webapp.WSGIApplication([('/customer/create', CustomerCreate),
                                      ('/customer/list', CustomerList)],
                                     debug=True)
    
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
  main()